"""
*******************************************************************************
                读取配置文件工具
*******************************************************************************
"""


class Properties:
    def __init__(self, filename, encoding='utf-8'):
        self.fp_write = None
        self.filename = filename
        self.fp_read = open(self.filename, 'r', encoding=encoding)
        self.data = self.fp_read.readlines()
        self.fp_read.close()
        self.datas = {}
        for i in self.data:
            if '#' in i:
                continue
            sp = i.split('=')
            key = sp[0].replace(' ', '')
            value = sp[-1].replace('\n', '').strip()
            self.datas.update({key: value})

    def get(self, key):
        try:
            self.datas[key]
        except KeyError as error:
            print("未找到变量 --> ", error)

        return self.datas[key]

    # 根据 key 获取 value 若未找到 返回 空
    def get_un_exception(self, key):
        data = None
        try:
            data = self.datas[key]
        except KeyError as error:
            print("未找到变量 --> ", error)

        return data

    def set(self, key, value):
        self.fp_write = open(self.filename, 'w', encoding='utf-8')
        try:
            self.datas[key] = value
        except KeyError as e:
            print("KeyError  -->  ", e)
        data = ""
        for k, v in self.datas.items():
            data += k + " = " + v + "\n"

        self.fp_write.writelines(data[:-1])
        self.fp_write.close()
